package com.kbt.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.commont.Constants;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.YZCodeBean;
import com.kbt.model.data.YZCodeBeans;
import com.kbt.net.RequestManager;
import com.kbt.util.tool.BtnSetting;
import com.kbt.util.tool.TimeCountUtil;
import com.kbt.util.tool.UUIDUtilTool;
import com.kbt.util.utils.MD5Utils;
import com.kbt.util.utils.Utils;
import org.w3c.dom.Text;

import javax.sql.RowSetListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhgk
 * @package: com.kbt.activity
 * @TODO: 忘记密码页面
 * @data: 2015/8/15 16:22
 * @version: V1.0
 */
public class ForgotPassWordActivity extends Activity implements RequestManager.ResponseInterface{

    private BaseBean baseBean;
    private RequestManager mRequestManager;
    private Map<String,String> postMap=null;
    private Map<String,Object> map =null;
    private YZCodeBeans yzCodeBeans;
    private YZCodeBean yzCodeBean;
    private  EditText phoneEdit;
    private EditText et_input_getImageCode;
    private ImageView imageCode;
    private String uuId;
    private TimeCountUtil timer;
    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.login_forgot_pass);

        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.login_forgot_pass);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不创建地址
                setResult(RESULT_CANCELED, null);
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("重置密码");
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        postMap = new HashMap<String, String>();
        map = new HashMap<String,Object>();
        uuId= UUIDUtilTool.getUUID();
        // 访问网络能在主程序中进行
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
        //初始化布局视图
        initView();
        //监听
        setListener();
    }
    //监听
    private void setListener(){
        imageCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uuId= UUIDUtilTool.getUUID();
                String urlString = Constants.ServiceInterFace.ServerURL + "rest/api/v1.1/valid_code?valid_code_id="+uuId;
                URL imageUrl = null;
                Bitmap bitmap = null;
                try{
                    imageUrl = new URL(urlString);
                }catch (MalformedURLException e) {
                    // TODO: handle exception
                    Log.e("TAG", "MalformedURLException");
                    e.printStackTrace();
                }
                try{
                    HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    //将得到的数据转换为InputStream
                    InputStream is = connection.getInputStream();
                    //将InputStream转换为Bitmap
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                }catch (IOException e) {
                    // TODO: handle exception
                    Log.e("TAG", "IOException");
                }
                if(bitmap == null){
                    Log.i("TAG", "没取到数据");
                }else{
                    imageCode.setImageBitmap(bitmap);
                }
            }
        });
    }

    /**
     * 初始化View
     **/
    private void initView() {

        phoneEdit = (EditText) findViewById(R.id.et_regist_phone_number);
        et_input_getImageCode = (EditText) findViewById(R.id.et_input_getImageCode);
        imageCode = (ImageView) findViewById(R.id.imageCode);
        final EditText validateEdit = (EditText) findViewById(R.id.bt_get_verification_code);
        final EditText newPassEdit = (EditText) findViewById(R.id.et_regist_password);
        final EditText confirmPassEdit = (EditText) findViewById(R.id.et_comfire_password);

        String urlString = Constants.ServiceInterFace.ServerURL + "rest/api/v1.1/valid_code?valid_code_id="+uuId;
        URL imageUrl = null;
        Bitmap bitmap = null;
        try{
            imageUrl = new URL(urlString);
        }catch (MalformedURLException e) {
            // TODO: handle exception
            Log.e("TAG", "MalformedURLException");
            e.printStackTrace();
        }
        try{
            HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
            connection.setDoInput(true);
            connection.connect();
            //将得到的数据转换为InputStream
            InputStream is = connection.getInputStream();
            //将InputStream转换为Bitmap
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }catch (IOException e) {
            // TODO: handle exception
            Log.e("TAG", "IOException");
        }
        if(bitmap == null){
            Log.i("TAG", "没取到数据");
        }else{
            imageCode.setImageBitmap(bitmap);
        }

        //计时按钮
        Button timeBtn = (Button) findViewById(R.id.bt_regist_get_verification_code);
        timeBtn.setText("获取验证码");
//        BtnSetting.setBtnBackground(timeBtn, 2, Color.RED, Color.RED, 8);
        timeBtn.setTextColor(Color.WHITE);
        //有效期2分钟
         timer = new TimeCountUtil(timeBtn, 120000, 1000);
        timeBtn.setClickable(true);
        timeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneValue = phoneEdit.getText().toString().trim();
                String imageCode =et_input_getImageCode.getText().toString().trim();
                if (imageCode.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入图片验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //对手机号的正确性校验,对手机号是否存在校验
                if (phoneValue.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                httpYanZhengCode(imageCode);
            }
        });

        //提交按钮
        TextView restBtn = (TextView) findViewById(R.id.tv_regist_commit);
        restBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneValue = phoneEdit.getText().toString().trim();
                String validValue = validateEdit.getText().toString().trim();
                String newPass = newPassEdit.getText().toString().trim();
                String imageCode =et_input_getImageCode.getText().toString().trim();
                String confirmPass = confirmPassEdit.getText().toString().trim();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String time = df.format(new Date());
                if (phoneValue.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (newPass.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入密码！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (confirmPass.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入密码确认", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!confirmPass.equals(newPass)) {
                    Toast.makeText(v.getContext(), "两次密码输入不一致,请重新输入密码!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (imageCode.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入图片验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (validValue.length() == 0) {
                    Toast.makeText(v.getContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }


                String Md5Password = MD5Utils.Md5(newPass);
                String Md5ConfirmPassword = MD5Utils.Md5(confirmPass);
                //修改密码
                httpUpdatePassword(phoneValue,validValue,Md5Password,imageCode);
            }
        });

    }
    //判断两个时间
    public static int compare_date(String DATE1, String DATE2) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }
    //获取验证码
    private void httpYanZhengCode(String imageCode){
        if(Utils.isNetworkAvailable(ForgotPassWordActivity.this)) {
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.getCodeURL + phoneEdit.getText().toString() + "&valid_code_value="+imageCode+"&valid_code_id="+uuId, Constants.RequestTag.getCodeTag, map, BaseBean.class);
        }else{
            Toast.makeText(ForgotPassWordActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //忘记密码
    private void httpUpdatePassword(String phoneValue,String validValue,String newPass,String imageCode){
        if(Utils.isNetworkAvailable(ForgotPassWordActivity.this)) {
            postMap.clear();
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", phoneValue);
            dataMap.put("user_password", newPass);
            dataMap.put("user_code", validValue);
            dataMap.put("valid_code_id", uuId);
            dataMap.put("valid_code_value",imageCode);
            postMap.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.forgotPasswordURL, postMap, Constants.RequestTag.forgotPasswordTag, BaseBean.class);
        }else{
            Toast.makeText(ForgotPassWordActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        if (tag == Constants.RequestTag.getCodeTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    timer.start();
                    Toast.makeText(ForgotPassWordActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(ForgotPassWordActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.forgotPasswordTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    Toast.makeText(ForgotPassWordActivity.this,"修改密码成功",Toast.LENGTH_SHORT).show();
                    finish();
                }else{
                    Toast.makeText(ForgotPassWordActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        Toast.makeText(ForgotPassWordActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
}
